package com.jeespring.elasticsearch.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jeespring.elasticsearch.dao.UserDao;
import com.jeespring.elasticsearch.dto.UserIndexDTO;
import com.jeespring.elasticsearch.entity.User;
import com.jeespring.elasticsearch.repository.UserRepository;
import com.jeespring.elasticsearch.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description UserServiceImpl
 * @author 张朝阳
 * @date 2021/2/15 23:11
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRepository userRepository;


    public PageInfo selectAllByPage(User user, int pageNumber, int pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<User> userList = userDao.select(user);
        PageInfo page = new PageInfo(userList);
        return page;
    }

    public void syncAll() {
        User user = new User();
        int pageNumber = 1;
        int pageSize = 500;
        PageHelper.startPage(pageNumber, pageSize);
        List<User> userList = userDao.select(user);
        PageInfo page = new PageInfo(userList);
        saveAll(userList);
        int pages = page.getPages();
        for (int i = 2; i <= pages; i++) {
            PageHelper.startPage(i, pageSize);
            userList = userDao.select(user);
            saveAll(userList);
        }
    }

    public void saveAll(List<User> userList ){
        List<UserIndexDTO> userIndexDTOList = new ArrayList<>();
        for (User user1 : userList) {
            UserIndexDTO userIndexDTO = new UserIndexDTO();
            BeanUtils.copyProperties(user1,userIndexDTO);
            userIndexDTOList.add(userIndexDTO);
        }
        userRepository.saveAll(userIndexDTOList);
    }
}
